import {PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message } from 'antd';
import React, { useState, useRef } from 'react';
import { Dispatch,connect } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm, { FormValueType } from './components/UpdateForm';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule ,exportUsers} from './service';
import { _local } from '@/utils/localStorage';
const moment = require('moment');
interface exportProps {
  dispatch: Dispatch;
}
/**
 * 添加节点
 * @param fields
 */

import UploadBasic from './UploadBasic';

const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  try {
    hide();
   const data = await addRule({ ...fields });
   if(data.status===406){
    message.error('操作失败，请重试!');
    return false;
   }
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule({
      nickName: fields.nickName,
      openid: fields.openid,
      gender: fields.gender,
      avatarUrl: fields.avatarUrl,
      id: fields.id,
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    const statusCode = await removeRule({
      id: selectedRows.id,
    });
    hide();

    if (statusCode.success == true) {
      message.success('删除成功，即将刷新');
      return true;
    } else {
      message.error('删除失败，请刷新后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const TableList: React.FC<exportProps> = (props) => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const exportUser =async ()=>{
    const hide = message.loading('正在导出。。。');
    const { dispatch } = props;
    const fileName = `用户账号管理${moment(new Date).format('YYYY-MM')}.xlsx`;
    dispatch({
      type: 'derive/deriveUser',
      callback: blob => { // 回掉将blob转为Excel文件下载
        console.log(blob)
        if (window.navigator.msSaveOrOpenBlob) {
          hide()
          navigator.msSaveBlob(blob, fileName);
          message.error('导出失败！');
        } else {
          hide()
          const link = document.createElement('a');
          const evt = document.createEvent('MouseEvents');
          link.style.display = 'none';
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          document.body.appendChild(link); // 此写法兼容可火狐浏览器
          evt.initEvent('click', false, false);
          link.dispatchEvent(evt);
          document.body.removeChild(link);
          message.success('导出成功！');
        }
      },
    });
    // try {
    //   hide();
    //   message.success('导出成功！');
    // } catch (error) {
    //   hide();
    //   message.error('导出失败！');
    // }
  }
  const columns: ProColumns<TableListItem>[] = [
    {
      title: 'Id',
      dataIndex: 'id',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
      valueType: 'textarea',
    },
    {
      title: '性别',
      dataIndex: 'gender',
    },
    {
      title: 'openid',
      dataIndex: 'openid',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <a
            onClick={async e => {
              await handleRemove(record);
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];
  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <UploadBasic />,
          <Button type="primary" onClick={() => exportUser()}>
            导出
          </Button>,
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => (
          <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项&nbsp;&nbsp;
            <span>用户 {selectedRows.reduce((pre, item) => pre + item.callNo, 0)}</span>
          </div>
        )}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable<TableListItem, TableListItem>
          onSubmit={async value => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
          rowSelection={{}}
        />
      </CreateForm>
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);

            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
    </PageHeaderWrapper>
  );
};

export default connect(() => ({
}))(TableList);
